package org.brisling.medical.queryService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.util.DateUtil;
import org.brisling.medical.domain.BasePatientInfo;
import org.brisling.medical.service.BasePatientInfoService;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * <p>Title: QueryBasePatientInfoService</p>
 * <p>Description: 全院基本业务信息查询service</p>
 * <p>Company: tongking</p>
 * @author trastor
 * @since 1.0
 * @version 1.0
 * @date 2016年7月20日 下午10:02:55
 */
@RestController
@RequestMapping("/basePatientInfo/query")
public class QueryBasePatientInfoService extends AbstractBaseQueryService<BasePatientInfo>{
	
	@Autowired
	private BasePatientInfoService basePatientInfoService;
	
	@Autowired
	private QueryBasemedicalService qryBasemedicalService;
	@Autowired
	private QueryAntimedicalService qryAntimedicalService;
	@Autowired
	private QueryAntidoseService qryAntidoseService;
	@Autowired
	private QueryOverlayPrescribeService qryOverlayPrescribeService;
	@Autowired
	private QueryDictionaryService qryDictionaryService;
	@Autowired
	private QueryLargePositiveService qryLargePositiveService;
	@Autowired
	private QueryLargeCostService qryLargeCostService;
	@Autowired
	private QueryMedicalPathwayPatientConclusion qryPathwayPatientConclusion;
	@Autowired
	private ShiroSecurityService shiroSecurityService;
	
	private static Logger logger = LoggerFactory.getLogger(QueryBasePatientInfoService.class);
	
	private final static Integer PATIENT_OUT = 1;
	private final static Integer PATIENT_IN = 2;
	
	private final static Integer PATIENT_EMERGENCE = 3;
	
	public QueryBasePatientInfoService(){
		this.moduleName = ConstSysParam.MODULE_BASE_PATIENT_INFO;
		this.subSystem = ConstSysParam.SUBSYSTEM_MEDICAL;
		this.tableName = this.moduleName;
		this.clazz = BasePatientInfo.class;
		typeMap = this.getTypeMap(clazz);
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return this.getBizMainPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return this.getBizEditPage();
	}
	
	@RequestMapping("/popPage.action")
	public ModelAndView getPopPage(){
		String userid = shiroSecurityService.getCurrentUserIdentify();
		String _page = "popMain";
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			if(!isManageJob(userid)){				
				_page="popDetail";
			}					
		}
		return new ModelAndView("/medical/medical_base_patient_info/"+_page);
	}
	
	@RequestMapping("/popInpatientPage.action")
	public ModelAndView getPopInpatientPage(){
		String userid = shiroSecurityService.getCurrentUserIdentify();
		String _page = "popInpatientMain";
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			if(!isManageJob(userid)){				
				_page="popInpatientDetail";
			}		
		}
		return new ModelAndView("/medical/medical_base_patient_info/"+_page);
	}
	
	@RequestMapping("/getListDomain.action")
	public ListDomain<BasePatientInfo> getListDomain(@RequestBody(required=false) String body){		
		
		Map<String,Object> map = this.getBodyParam(body);
		String userid = shiroSecurityService.getCurrentUserIdentify();
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){			
			addJobDeptConditionToMap(userid,map,"dept_code");			
			//查找科室数据		
		}
		//查询表
		return super.getListDomainByConditionAndOrder(null, map, typeMap, orderMap, true);
		
		
	}
	
	/**
	 * 获取部门统计指标
	 * @param body
	 * @return
	 */
	@RequestMapping("/getDeptListDomain.action")
	public ListDomain<BasePatientInfo> getDeptListDomain(@RequestBody(required=false) String body){	
		
		
		Map<String,Object> map = this.getBodyParam(body);
		
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,String> paramMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);
		
		String dataType = "1";
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			if(isManageJob(userid)){
				String deptids = this.getJobDeptidAndAccountDeptids(userid);
				paramMap.put("dept_code_in", deptids);
				dataType = "2";
			}else{
				
				paramMap.put("doct_code", userid);
				dataType = "3";
			}
			//查找科室数据		
		}else{
			paramMap.put("dept_code_in", "-1");
			dataType = "1";
		}		
		paramMap.put("data_type", dataType);
		
		//查询表
		return super.getListDomainByConditionAndOrder(null, map, typeMap, orderMap, true);
		
	}
	
	@RequestMapping("/getIndicateListDomain.action")
	public HashMap<String,Object> getIndicateListDomain(@RequestBody(required=false) String body){	
		
		HashMap<String,Object> map = new HashMap<String,Object>();
		map.put("base_medical", qryBasemedicalService.getAllListDomain(body));
		map.put("anti_medical", qryAntimedicalService.getAllListDomain(body));
		map.put("anti_dose", qryAntidoseService.getDeptListDomain(body));
		map.put("overlay_prescribe", qryOverlayPrescribeService.getAllListDomain(body));
		map.put("large_positive", qryLargePositiveService.getAllListDomain(body));
		map.put("large_cost", qryLargeCostService.getAllListDomain(body));
		map.put("pathway_patient", qryPathwayPatientConclusion.getAllListDomain(body));
		return map;
	}
	
	/**
	 * 获取部门统计指标
	 * @param body
	 * @return
	 */
	
	private List<BasePatientInfo> getList(String monitor_year_month){
		
		String sql = String.format("select * from %1$s where monitor_year_month='%2$s'",this.tableName,monitor_year_month); 
		//查询表
		return super.getAllList(sql);
		
	}
	
	/**
	 * 查询实时数据
	 * @param body
	 * @return
	 */
	@RequestMapping("/getRealTimeListDomain.action")
	public ListDomain<BasePatientInfo> getRealTimeListDomain(@RequestBody(required=false) String body){		
		Map<String,Object> paramMap = this.getBodyParam(body);
		
		String[] monitorDate = super.getMonitorDate(paramMap);
		if(monitorDate!=null && monitorDate.length>1){			
			
			String start = monitorDate[0];
			String end = monitorDate[1];
			String year_month = monitorDate[2];
			List<BasePatientInfo> inlists =countBaseMedicalInpatient (year_month,start,end);
			
			if(inlists!=null){
				
				basePatientInfoService.save(inlists);
				
				return super.getListDomainByConditionAndOrderUseTable(body, typeMap, orderMap,true);
			}					
			
		}
		//查询表
		
		return new ListDomain<BasePatientInfo>();
	}
	
	
	public void autoTask(Integer year,Integer month){
		this.autoMonitor(year, month);
		this.autoUpdateStandard(year, month);
	}
	/**
	 * 执行自动统计
	 */
	public void autoMonitor(Integer year,Integer month){
		String[] yestodayMonth = null;
		if(year ==null || month ==null)
			yestodayMonth = DateUtil.getYestodayMonthDay();
		else{
			yestodayMonth = DateUtil.getMonthDay(year, month);
		}
		
		List<BasePatientInfo> inlists = countBaseMedicalInpatient(yestodayMonth[2],yestodayMonth[0],yestodayMonth[1]);
		
		List<BasePatientInfo> outlists = countBaseMedicalOutpatient(yestodayMonth[2],yestodayMonth[0],yestodayMonth[1]);
		
		//查询已有数据
		List<BasePatientInfo> oldLists = this.getList(yestodayMonth[2]);
		LinkedHashMap<String,BasePatientInfo> lmap = new LinkedHashMap<String,BasePatientInfo>();
		
		//将已有值存入临时map
		if(oldLists!=null && oldLists.size()>0){
			
			for(int i=0;i<oldLists.size();i++){
				BasePatientInfo b = oldLists.get(i);
				String _key = null;
				if(!b.getData_type().equals("3")){
					_key = b.getDept_code()+"-"+b.getPatient_type();
				}else{
					if(b.getDoct_code()==null){
						logger.error("doct_code is null. There is somthing happend on earth.");
						continue;
					}
					_key = b.getDept_code() +"-" + b.getDoct_code()+"-"+b.getPatient_type();
				}
				lmap.put(_key, b);
			}
		}
		
		
		if(inlists!=null || outlists!=null){
			inlists.addAll(outlists);
			if(lmap!=null && lmap.size()>0){
				for(int i=0;i<inlists.size();i++){
					BasePatientInfo b = inlists.get(i);
					String _key = null;
					if(!b.getData_type().equals("3")){
						_key = b.getDept_code()+"-"+b.getPatient_type();
					}else{
						if(b.getDoct_code()==null){
							logger.error("doct_code is null. There is somthing happend on earth.");
							continue;
						}
						_key = b.getDept_code() +"-" + b.getDoct_code()+"-"+b.getPatient_type();
					}
					if(lmap.containsKey(_key)){
						inlists.get(i).setId(lmap.get(_key).getId());
					}
				}
			}
			basePatientInfoService.save(inlists);	
			
		}	
	}
	
	public void autoUpdateStandard(Integer year,Integer month){
		String[] yestodayMonth = null;
		if(year ==null || month ==null)
			yestodayMonth = DateUtil.getYestodayMonthDay();
		else{
			yestodayMonth = DateUtil.getMonthDay(year, month);
		}
		basePatientInfoService.updateStandard(yestodayMonth[2]);
	}
	
	/**
	 * 统计基本药物住院缓存信息
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public List<BasePatientInfo> countBaseMedicalInpatient(String year_month,String startDate ,String endDate){
		
			
		
		String[] sqlids = {"base_inpatient_info_all","base_inpatient_info_dept","base_inpatient_info_doct"};
		//统计全院数据-住院
		
		List<String> sqls = new ArrayList<String>();
		for(int i = 0;i<sqlids.length;i++){
			String sql = qryDictionaryService.getSqlByBizcode(sqlids[i]);
			if(sql!=null){
				sqls.add(sql);
			}
		}
		//所有数据
		List<BasePatientInfo> lists = super.monitorCountBase(year_month,startDate,endDate,sqls);		
		
		return lists;
		
	}	
	
	/**
	 * 统计基本药物住院缓存信息
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public List<BasePatientInfo> countBaseMedicalOutpatient(String year_month,String startDate ,String endDate){
		
			
		
		String[] sqlids = {"base_outpatient_info_all","base_outpatient_info_dept","base_patient_info_doct"};
		//统计全院数据-住院
		
		List<String> sqls = new ArrayList<String>();
		for(int i = 0;i<sqlids.length;i++){
			String sql = qryDictionaryService.getSqlByBizcode(sqlids[i]);
			if(sql!=null){
				sqls.add(sql);
			}
		}
		//所有数据
		List<BasePatientInfo> lists = super.monitorCountBase(year_month,startDate,endDate,sqls);		
		
		return lists;
		
	}	
	
	/**
	 * 根据用户id查找用户信息
	 * @param id	用户id
	 * @return 用户信息记录 
	 */
	@RequestMapping("/getOne.action")
	public BasePatientInfo getOne(@RequestParam(value="id",required=false) Long id){
				
		return super.getOne(id);
	}
	
	/**
	 * 根据用户唯一编码查找用户信息
	 * @param identify	用户唯一编码
	 * @return 用户信息记录
	 */
	@RequestMapping("/getOneByIdentify.action")
	public BasePatientInfo getOneByIdentify(@RequestParam(value="identify",required=false) String identify){	
		return super.getOneByIdentify(identify);
	}
	
	
}
